<template>
  <div @click="handleClick">App {{ count }} {{ oddOrEven }}</div>
  <ul>
    <li v-for="(value, key) in person" :key="key">{{ key }} - {{ value }}</li>
  </ul>
  <button @click="person.age++">更新年龄</button>
  <Child :count="count" :person="person" @setCount="handleClick" />
</template>

<script lang="ts">
import {
  ref,
  reactive,
  watch,
  computed,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
} from "vue";
import Child from "./Child.vue";

// components props emits 生命周期函数
/*
  组合式API生命周函数：
    初始化渲染阶段
      setup --> 取代了 beforeCreate created
      onBeforeMount
      onMounted
    更新阶段
      onBeforeUpdate
      onUpdated
    卸载阶段
      onBeforeUnmount
      onUnmounted
*/

export default {
  name: "App",
  setup() {
    console.log("setup");

    // 生命周期函数(允许定义多个)
    // onBeforeMount(() => {
    //   console.log("onBeforeMount");
    // });
    onMounted(() => {
      console.log("onMounted111");
    });
    onMounted(() => {
      console.log("onMounted222");
    });
    // onBeforeUpdate(() => {
    //   console.log("onBeforeUpdate");
    // });
    // onUpdated(() => {
    //   console.log("onUpdated");
    // });
    // onBeforeUnmount(() => {
    //   console.log("onBeforeUnmount");
    // });
    // onUnmounted(() => {
    //   console.log("onUnmounted");
    // });

    const count = ref(0);
    const handleClick = () => {
      count.value++;
    };
    // 监视属性
    watch(
      count,
      (newVal, oldVal) => {
        console.log(newVal, oldVal);
      },
      {
        // deep: true, // 深度监视
        immediate: true, // 立即监视
      }
    );

    // 只读计算属性
    const oddOrEven = computed(() => {
      return count.value % 2 === 0 ? "偶数" : "奇数";
    });

    // 可读可写计算属性
    // const xxx = computed({
    //   get() {},
    //   set() {},
    // });

    const person = reactive({
      name: "jack",
      age: 18,
    });
    // 监视对象直接监视
    // watch(person, (newVal, oldVal) => {
    //   console.log(newVal, oldVal);
    // });
    // 监视对象上的属性变化，需要写成函数形式
    watch(
      () => person.age,
      (newVal, oldVal) => {
        console.log(newVal, oldVal);
      }
    );

    return {
      count,
      person,
      oddOrEven,
      handleClick,
    };
  },
  components: {
    Child,
  },
};
</script>

<style></style>
